package com.erpanderp.wam.ac.view.travel;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.swing.SwingWorker;

import com.erpanderp.wam.ac.model.entity.travel.TravelLogistics;
import com.erpanderp.wam.ac.model.entity.travel.TravelRequest;
import com.erpanderp.wam.ac.model.service.travel.TravelRequestDAO;
import com.erpanderp.wam.util.CommonLookup;
import com.erpanderp.wam.util.EmailUtil;
import com.erpanderp.wam.util.ValidationUtil;
import com.erpanderp.wam.util.WAMHostManager;

@ManagedBean
@ViewScoped
public class ApproveTravelRequestBean {
	
	HttpSession session = (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(true);
	HttpServletRequest request = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();
	ServletContext context = (ServletContext) FacesContext.getCurrentInstance().getExternalContext().getContext();
	
	private TravelRequest travelRequest;
	private List<TravelLogistics> travelLogistics = new ArrayList<TravelLogistics>();
	
	TravelRequestDAO travelRequestDAO = new TravelRequestDAO();
	
	EmailUtil emailUtil;
	String EMAIL_MESSAGE;
	
	public ApproveTravelRequestBean(){
		String travelRequestCode = request.getParameter("trcode");  
		if(travelRequestCode != null && !travelRequestCode.equals("")){
			travelRequest = travelRequestDAO.getTravelRequest(travelRequestCode);
			if(travelRequest == null){
				gotoLoginPage();
			}else if(travelRequest.getTravelStatus().equals(CommonLookup.TRAVEL_REQUEST_STATUS_INPROCESS)){
				travelLogistics.addAll(travelRequest.getTravelLogistics());
			}			
		}else{
			gotoLoginPage();
		}
	}

	private void gotoLoginPage(){
		try {
			FacesContext.getCurrentInstance().getExternalContext().redirect("/wam/login.html");
		} catch (IOException e) {				
			e.printStackTrace();
		}
	}
	
	public void approveTravelRequest(ActionEvent e){
		if(validate()){
			travelRequest.setDateModified(new Date());
			travelRequest.setModifiedBy(travelRequest.getApprover().getFirstName());
			travelRequest.setTravelStatus(CommonLookup.TRAVEL_REQUEST_STATUS_APPROVED);
			if(travelRequestDAO.updateTravelRequest(travelRequest) != null){
				FacesContext.getCurrentInstance().addMessage("", new FacesMessage(FacesMessage.SEVERITY_INFO, "Travel request is approved.", ""));
				System.out.println(sendMessage());
			}	
		}
	}
	
	public void rejectTravelRequest(ActionEvent e){
		if(validate()){
			travelRequest.setDateModified(new Date());
			travelRequest.setModifiedBy(travelRequest.getApprover().getFirstName());
			travelRequest.setTravelStatus(CommonLookup.TRAVEL_REQUEST_STATUS_REJECTED);
			if(travelRequestDAO.updateTravelRequest(travelRequest) != null){
				FacesContext.getCurrentInstance().addMessage("", new FacesMessage(FacesMessage.SEVERITY_INFO, "Travel request is rejected.", ""));
				System.out.println(sendMessage());
			}	
		}
		
	}
	
	private boolean validate(){
		if(ValidationUtil.isEmpty(travelRequest.getApprovalComments(), "Comments ", "", FacesContext.getCurrentInstance()) != null){
			return false;
		}else{
			return true;
		}
	}
	
	public String sendMessage(){
		
		Map<String, String> hostsMap = WAMHostManager.getWAMHosts(context);
		
		emailUtil = new EmailUtil();
		if (hostsMap.get(CommonLookup.DEV_EMAIL) == null) {
			String[] to = { travelRequest.getEmployee().getFirstName() };
			emailUtil.setRecieverAddresses(to);
		} else {
			String[] to = { hostsMap.get(CommonLookup.DEV_EMAIL) };
			System.out.println(to);
			emailUtil.setRecieverAddresses(to);
		}
		
		
		String messageString = "Dear " + travelRequest.getEmployee().getFirstName() + " " + travelRequest.getEmployee().getLastName() + "<br />";
		SimpleDateFormat format = new SimpleDateFormat("dd-MMM-yyyy");
		if(travelRequest.getTravelStatus().equals(CommonLookup.TRAVEL_REQUEST_STATUS_APPROVED)){
			messageString += "<p>Your Travel Request " + travelRequest.getTravelRequestCode() + " is approved from " + format.format(travelRequest.getPeriodFrom()) + " to " + format.format(travelRequest.getPeriodTo()) + ".</p>"; 
		}else{
			messageString += "<p>Your Travel Request " + travelRequest.getTravelRequestCode() + " is rejected.</p>";
		}
						
		System.out.println(travelRequest.getApprovalComments());
		messageString += "<span style='font-weight: bold;'>Approval Comment: </span>" + travelRequest.getApprovalComments() +						
								"<br /><br />"+								
								"Thanks & Regards, <br />"+CommonLookup.WAM_DEVTEAM_SIGNATURE;;
		
		emailUtil.setMessage(messageString);
		emailUtil.setSenderEmail("podquick@erpanderp.com", "WAM - Dev Team");
		emailUtil.setSubject("WAM - Travel Request (" + travelRequest.getTravelRequestCode() + ")");

		SwingWorker worker = new SwingWorker<String, Object>() {
			@Override
			protected String doInBackground() throws Exception {
				EMAIL_MESSAGE = emailUtil.processAndSendEmail();
				return null;
			}

			@Override
			protected void done() {
					System.out.println("DONE " + EMAIL_MESSAGE);		
			}
		};
		worker.execute();
		System.out.println( "BEFORE RETURNING: " + EMAIL_MESSAGE);
		return EMAIL_MESSAGE;
	}
	
	public TravelRequest getTravelRequest() {
		return travelRequest;
	}

	public void setTravelRequest(TravelRequest travelRequest) {
		this.travelRequest = travelRequest;
	}

	public List<TravelLogistics> getTravelLogistics() {
		return travelLogistics;
	}

	public void setTravelLogistics(List<TravelLogistics> travelLogistics) {
		this.travelLogistics = travelLogistics;
	}
	
}
